package com.maltys.dp.backpack;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/last-stone-weight-ii/">最后一块石头的重量II</a>
 */
public class LastStoneWeightII {
    public int lastStoneWeightII(int[] stones) {
        int sum = 0;
        for (int stone : stones) {
            sum += stone;
        }
        int[][] dp = new int[stones.length][sum / 2 + 1];
        for (int i = stones[0]; i <= sum / 2; i++) {
            dp[0][i] = stones[0];
        }
        for (int i = 1; i < stones.length; i++) {
            for (int j = 1; j <= sum / 2; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j >= stones[i]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - stones[i]] + stones[i]);
                }
            }
        }
        return Math.abs(sum - dp[stones.length - 1][sum / 2] * 2);
    }

    public static void main(String[] args) {
        LastStoneWeightII weightII = new LastStoneWeightII();
        int stoneWeightII = weightII.lastStoneWeightII(new int[]{31,26,33,21,40});
        System.out.println(stoneWeightII);
    }
}
